//
//  FirstLogViewController.m
//  SIPphone
//
//  Created by wrt on 14-3-21.
//  Copyright (c) 2014年 wrtsoft. All rights reserved.
//

#import "FirstLogViewController.h"
#import "TPKeyboardAvoidingScrollView.h"

#import "AppDelegate.h"

#import "ContactsDateBase.h"
#import "PromptChatDateBase.h"
#import "PostMessageDataBase.h"
#import "FriendRespondDateBase.h"
#import "HistoryDataBase.h"

#import "SimplePingHelper.h"
#import "Reachability.h"

@interface FirstLogViewController ()
@property (nonatomic) Reachability *netReachability; //用于判断网络连接状态
@end

@implementation FirstLogViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.scrollView contentSizeToFit];
    self.isAutoRegister = NO;
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    self.ipAds = [[NSString alloc] init];
    self.port = [[NSString alloc] init];
    self.ipAds = [defaults objectForKey:@"SAVEIPADDRESS"];
    self.port = [defaults objectForKey:@"SAVEPORT"];
    
    NSString *tempUserName = [[NSString alloc] init];
    tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
    NSString *tempPassWord = [[NSString alloc] init];
    tempPassWord = [defaults valueForKey:@"SAVEPASSWORD"];
    
    
    if (tempUserName.length > 0 && tempPassWord.length > 0)
    {
        self.userNameField.text = tempUserName;
        self.passWordField.text = tempPassWord;
    }
    

    
    //设置一个能判断网络的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    //设置判断网络是否连接的通知
    self.netReachability = [Reachability reachabilityForInternetConnection];
	[self.netReachability startNotifier];
	[self updateInterfaceWithReachability:self.netReachability];
    
    
    
//    BOOL isConnectNet = [defaults boolForKey:@"ISREACHABILITY"];
//    if (isConnectNet == YES)
//    {
//        [self pingAddress:self.ipAds];
//    }
//    else
//    {
//        [self.statusLable setHidden:NO];
//        self.statusLable.text = @"系统检测到设置未连接网络，请连接网络后再进行登录";
//    }
}




- (IBAction)logButtonPressed:(id)sender
{
    if (self.userNameField.text.length > 0 && self.passWordField.text.length > 0)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL isConnectNet = [defaults boolForKey:@"ISREACHABILITY"];
        if (isConnectNet == YES)
        {
            if (self.isPingSuccess)
            {
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                app.isFristOpen = 1;
//                SIPInterface *interface = [SIPInterface shareSIPInterface];
//                [interface closeRegisterUsers];
                //弹出警告窗口
                self.alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"loading", @"登录中 Loading") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
                [self.alertView show];
                //在里面加入旋转
                UIActivityIndicatorView *activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
                //开始转
                [activeView startAnimating];
                activeView.center = CGPointMake(self.alertView.bounds.size.width/2,self.alertView.bounds.size.height-40.0f);
                [self.alertView addSubview:activeView];
                
                dispatch_async(dispatch_get_main_queue(),^{
                    [self performSelector:@selector(agianRegisterUser) withObject:self afterDelay:2];
                });
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"under the current state of the network can not connect to the server, check whether the network can connect to the Internet", @"当前网络状态下不能连接到服务器，请检查网络是否能连接到互联网 Under the current state of the network can not connect to the server, check whether the network can connect to the Internet") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
                [alert show];
            }
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please try again connect to the network", @"请连接网络再进行尝试 Please try again connect to the network") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
            [alert show];
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please fill out the complete contents", @"请将内容填写完整 Please fill out the complete contents") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    }
}

- (void)agianRegisterUser
{
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface register:self.userNameField.text passWord:self.passWordField.text];
    [interface displayName:self.userNameField.text andUserName:self.userNameField.text];
    [interface setServiceAddress:self.ipAds andPort:[self.port intValue]];
//    [interface startRegisterUsers];
}


- (IBAction)autoLoginButtonPressed:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //根据是否选中去改变按钮的图样，和将yes或者no存起来以便程序下次启动时不用再次手动登陆
    if (!self.isAutoRegister)
    {
        [defaults setBool:YES forKey:@"ISAUTOREGISTERSTATUS"];
        [self.isAutoLogButton setBackgroundImage:[UIImage imageNamed:@"选中.png"] forState:UIControlStateNormal];
    }
    else if(self.isAutoRegister)
    {
        [defaults setBool:NO forKey:@"ISAUTOREGISTERSTATUS"];
        [self.isAutoLogButton setBackgroundImage:[UIImage imageNamed:@"选择.png"] forState:UIControlStateNormal];
    }
    [defaults synchronize];
    self.isAutoRegister = !self.isAutoRegister;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -
#pragma mark pingMethod
- (void)pingAddress:(NSString *)addr
{
    [SimplePingHelper ping:addr target:self sel:@selector(pingResult:)];
}

// callback
- (void)pingResult:(NSNumber*)success
{
    if (success.boolValue)
    {
        self.isPingSuccess = YES;
        [self.statusLable setHidden:YES];
    }
    else
    {
        self.isPingSuccess = NO;
        [self.statusLable setHidden:NO];
        self.statusLable.text = NSLocalizedString(@"under the current state of the network can not connect to the server, check whether the network can connect to the Internet", @"当前网络状态下不能连接到服务器，请检查网络是否能连接到互联网 Under the current state of the network can not connect to the server, check whether the network can connect to the Internet");
    }
}

#pragma mark -
#pragma mark reachabilityMethod
//接收到通知传过来的网络状态变化
- (void)reachabilityChanged:(NSNotification *)note
{
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
	[self updateInterfaceWithReachability:curReach];
}
//对应的变化做处理
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if (reachability == self.netReachability)
	{
		NetworkStatus netStatus = [reachability currentReachabilityStatus];
        BOOL connectionRequired = [reachability connectionRequired];
        
        switch (netStatus)
        {
            case NotReachable:
            {
                NSLog(@"没有网络");
                connectionRequired = NO;
                break;
            }
                
            case ReachableViaWWAN:
            {
                NSLog(@"WWAN");
                connectionRequired = YES;
                break;
            }
            case ReachableViaWiFi:
            {
                NSLog(@"WIFI");
                connectionRequired = YES;
                break;
            }
        }
        
        if (connectionRequired)
        {
            [self.statusLable setHidden:YES];
            [defaults setBool:YES forKey:@"ISREACHABILITY"];
            NSLog(@"连接上的哦");
            [self pingAddress:self.ipAds];
        }
        else
        {
            [self.statusLable setHidden:NO];
            self.statusLable.text = NSLocalizedString(@"the system detects the settings are not connected to the network, connect the network and then log", @"系统检测到设置未连接网络，请连接网络后再进行登录 The system detects the settings are not connected to the network, connect the network and then log");
            [defaults setBool:NO forKey:@"ISREACHABILITY"];
        }
    }
    [defaults synchronize];
}

#pragma mark -
#pragma mark SIPListenMethod
- (void)registerSuccessful //当注册成功时
{
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.isFristOpen == 1)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //个人状态 设置在线
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setMyStatusWithInt:1];
        [defaults setInteger:1 forKey:@"SAVEMYSTATUS"];
        app.isFristOpen++;
        
        //创建用于存储联系人的数据库
        ContactsDateBase *contactsDb = [ContactsDateBase shareContactsDataBase];
        [contactsDb changeTableName:self.userNameField.text];
        [contactsDb creatDB];
        [contactsDb readDB];
        
        //创建用于存储好友信息的数据库
        FriendRespondDateBase *friendRespondDB = [FriendRespondDateBase shareFriendRespondDateBase];
        [friendRespondDB changeTableName:self.userNameField.text];
        [friendRespondDB creatDB];
        [friendRespondDB readDB];
        
        //创建用于即时聊天的数据库
        PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
        [promptDB changeTableName:self.userNameField.text];
        [promptDB creatDB];
        [promptDB readDB];
        
        //创建用于历史记录的数据库
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB changeTableName:self.userNameField.text];
        [historyDB createDb];
        [historyDB loadArray:0];
        
        //创建用于推送消息的数据库
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB changeTableName:self.userNameField.text];
        [postMsgDB createDb];
        [postMsgDB loadArray];
        
        
        //        NSMutableArray *tempUserNameArray = [[NSMutableArray alloc] init];
        //        NSMutableArray *tempIpArray = [[NSMutableArray alloc] init];
        
        //将列表中的好友传到底层去
        //        for (int i = 0; i < contactsDb.isFriendArray.count; i++)
        //        {
        //            if ([contactsDb.isFriendArray[i] isEqualToString:@"好友"])
        //            {
        //                [tempUserNameArray addObject:contactsDb.userNameArray[i]];
        //                [tempIpArray addObject:contactsDb.ipPortArray[i]];
        //            }
        //        }
        //
        //        for (int j = 0; j < tempUserNameArray.count; j++)
        //        {
        //            SIPInterface *interface = [SIPInterface shareSIPInterface];
        //            [interface addFriendsWithUserName:tempUserNameArray[j] andDisPlayName:@"" andIp:tempIpArray[j]];
        //        }
    }
    
    dispatch_async(dispatch_get_main_queue(),^{
        //在主线程中操作
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        NSString *userName = [[NSString alloc] init];
        userName = self.userNameField.text;
        NSString *passWord = [[NSString alloc] init];
        passWord = self.passWordField.text;
        NSString *displayName = [[NSString alloc] init];
        displayName = self.userNameField.text;

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:userName forKey:@"SAVEUSERNAME"];
        [defaults setObject:passWord forKey:@"SAVEPASSWORD"];
        [defaults setObject:displayName forKey:@"SAVEDISPLAYNAME"];
        //成功注册后将用户名和密码存起来
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UITabBarController *tabbarVC = [[UITabBarController alloc] init];
        tabbarVC = app.tabBarVC;
        tabbarVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:tabbarVC animated:YES];
        
        [defaults setObject:@"YES" forKey:@"FRISTLOGSUCCESS"];
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
        
        //注册报警服务器
        //=================================
        //报警配置
        //设置报警服务器地址和端口号
        NSString *alarmIPAddressStr = [[NSString alloc] init];
        alarmIPAddressStr = [defaults valueForKey:@"SAVEALARMIPADDRESS"];
        
        NSString *alarmIPPortStr = [[NSString alloc] init];
        alarmIPPortStr = [defaults valueForKey:@"SAVEALARMIPPORT"];
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        if (alarmIPPortStr.length > 0 && alarmIPAddressStr.length > 0 )
        {
            [interface setAlarmIPAddressAndPort:alarmIPAddressStr andPort:alarmIPPortStr];
        }
    });
}

- (void)registerFailed  //当注册失败时 弹出提醒框
{
    dispatch_async(dispatch_get_main_queue(),^{
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"registration fails, check to see if you enter an incorrect username and password, or a network connection error", @"注册失败，请检查是否输入了错误的用户名和密码，或者网络连接错误 Registration fails, check to see if you enter an incorrect username and password, or a network connection error") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    });
}


@end
